<template>
    <div class="dashboard-container">
        <!-- 数据概览卡片 -->
        <el-row :gutter="20">
            <el-col :span="6">
                <el-card class="data-card">
                    <template #header>
                        <div class="card-header">
                            <span>总数据量</span>
                            <el-tag size="small">今日</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ formatNumber(statistics.totalData) }}</h2>
                        <div class="trend">
                            <span :class="['trend-value', statistics.dataGrowth >= 0 ? 'positive' : 'negative']">
                                {{ statistics.dataGrowth > 0 ? '+' : '' }}{{ statistics.dataGrowth }}%
                            </span>
                            <span class="trend-label">较昨日</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            
            <el-col :span="6">
                <el-card class="data-card">
                    <template #header>
                        <div class="card-header">
                            <span>活跃用户</span>
                            <el-tag size="small" type="success">实时</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ formatNumber(statistics.activeUsers) }}</h2>
                        <div class="trend">
                            <span :class="['trend-value', statistics.userGrowth >= 0 ? 'positive' : 'negative']">
                                {{ statistics.userGrowth > 0 ? '+' : '' }}{{ statistics.userGrowth }}%
                            </span>
                            <span class="trend-label">较上周</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            
            <el-col :span="6">
                <el-card class="data-card">
                    <template #header>
                        <div class="card-header">
                            <span>分析任务</span>
                            <el-tag size="small" type="warning">进行中</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ statistics.runningTasks }}</h2>
                        <el-progress 
                            :percentage="statistics.taskProgress" 
                            :status="statistics.taskProgress === 100 ? 'success' : ''"
                        />
                    </div>
                </el-card>
            </el-col>
            
            <el-col :span="6">
                <el-card class="data-card">
                    <template #header>
                        <div class="card-header">
                            <span>系统状态</span>
                            <el-tag size="small" type="info">实时</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ statistics.systemStatus }}</h2>
                        <el-progress type="dashboard" :percentage="statistics.systemLoad" />
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="chart-row">
            <el-col :span="16">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>数据趋势分析</span>
                            <el-radio-group v-model="timeRange" size="small">
                                <el-radio-button label="week">周</el-radio-button>
                                <el-radio-button label="month">月</el-radio-button>
                                <el-radio-button label="year">年</el-radio-button>
                            </el-radio-group>
                        </div>
                    </template>
                    <div class="chart-container">
                        <v-chart :option="getTrendChartOption" autoresize />
                    </div>
                </el-card>
            </el-col>
            
            <el-col :span="8">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>数据来源分布</span>
                        </div>
                    </template>
                    <div class="chart-container">
                        <v-chart :option="getDistributionChartOption" autoresize />
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 最近任务列表 -->
        <el-card class="task-card">
            <template #header>
                <div class="card-header">
                    <span>最近任务</span>
                    <el-button type="primary" size="small" @click="refreshTasks">
                        刷新
                    </el-button>
                </div>
            </template>
            
            <el-table :data="recentTasks" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="任务名称" />
                <el-table-column prop="type" label="类型" width="120">
                    <template #default="scope">
                        <el-tag :type="getTaskTypeTag(scope.row.type)">
                            {{ scope.row.type }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="getStatusTag(scope.row.status)">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="progress" label="进度" width="180">
                    <template #default="scope">
                        <el-progress 
                            :percentage="scope.row.progress"
                            :status="getProgressStatus(scope.row.progress)"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180">
                    <template #default="scope">
                        {{ formatDate(scope.row.created_at) }}
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { analysisApi } from '@/api/analysis'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
    DataZoomComponent,
    ToolboxComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册必需的组件
use([
    CanvasRenderer,
    LineChart,
    PieChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
    DataZoomComponent,
    ToolboxComponent
])

// 统计数据
const statistics = ref({
    totalData: 0,
    dataGrowth: 0,
    activeUsers: 0,
    userGrowth: 0,
    runningTasks: 0,
    taskProgress: 0,
    systemStatus: '正常',
    systemLoad: 0
})

// 趋势数据
const trendData = ref({
    dates: [],
    data: [],
    engagement: [],
    growth: 0
})

// 来源分布数据
const sourceData = ref({
    labels: [],
    data: []
})

const timeRange = ref('week')

const recentTasks = ref([
    {
        id: 1,
        name: '微博数据采集',
        type: '数据采集',
        status: '进行中',
        progress: 45,
        created_at: '2024-02-08T10:00:00'
    },
    {
        id: 2,
        name: '情感分析',
        type: '数据分析',
        status: '已完成',
        progress: 100,
        created_at: '2024-02-08T09:30:00'
    },
    {
        id: 3,
        name: '用户画像分析',
        type: '数据分析',
        status: '等待中',
        progress: 0,
        created_at: '2024-02-08T09:00:00'
    }
])

const formatNumber = (num) => {
    return new Intl.NumberFormat().format(num)
}

const formatDate = (date) => {
    return new Date(date).toLocaleString()
}

const getTaskTypeTag = (type) => {
    const types = {
        '数据采集': 'primary',
        '数据分析': 'success',
        '报表生成': 'warning'
    }
    return types[type] || 'info'
}

const getStatusTag = (status) => {
    const statuses = {
        '进行中': 'primary',
        '已完成': 'success',
        '等待中': 'info',
        '失败': 'danger'
    }
    return statuses[status] || 'info'
}

const getProgressStatus = (progress) => {
    if (progress === 100) return 'success'
    if (progress === 0) return ''
    return 'primary'
}

// 自动刷新定时器
let refreshTimer = null

// 启动自动刷新
const startAutoRefresh = () => {
    // 每60秒刷新一次数据
    refreshTimer = setInterval(() => {
        fetchDashboardData()
        refreshTasks()
    }, 60000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
    if (refreshTimer) {
        clearInterval(refreshTimer)
        refreshTimer = null
    }
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
    try {
        // 获取统计数据
        const dashboardResponse = await analysisApi.getDashboardStats()
        if (dashboardResponse) {
            statistics.value = {
                totalData: dashboardResponse.total_data || 0,
                dataGrowth: dashboardResponse.data_growth || 0,
                activeUsers: dashboardResponse.active_users || 0,
                userGrowth: dashboardResponse.user_growth || 0,
                runningTasks: dashboardResponse.running_tasks || 0,
                taskProgress: dashboardResponse.task_progress || 0,
                systemStatus: dashboardResponse.system_status || '正常',
                systemLoad: dashboardResponse.system_load || 0
            }
        }

        // 获取趋势数据
        const trendResponse = await analysisApi.getTrendData()
        if (trendResponse) {
            trendData.value = {
                dates: trendResponse.dates || [],
                data: trendResponse.data || [],
                engagement: trendResponse.engagement || [],
                growth: trendResponse.growth || 0
            }
        }

        // 获取来源分布
        const distributionResponse = await analysisApi.getSourceDistribution()
        if (distributionResponse?.data) {
            sourceData.value = {
                labels: distributionResponse.data.map(item => item.name),
                data: distributionResponse.data.map(item => item.value)
            }
        }
    } catch (error) {
        console.error('Error fetching dashboard data:', error)
        ElMessage.error('获取仪表盘数据失败')
    }
}

// 刷新任务列表
const refreshTasks = async () => {
    try {
        const response = await analysisApi.getTasks()
        if (response?.results) {
            recentTasks.value = response.results.map(task => ({
                id: task.id,
                name: task.name,
                type: task.type,
                status: task.status,
                progress: task.progress,
                created_at: task.created_at
            }))
        }
        ElMessage.success('任务列表已更新')
    } catch (error) {
        console.error('Error refreshing tasks:', error)
        ElMessage.error('更新任务列表失败')
    }
}

// 在组件挂载时获取数据
onMounted(() => {
    fetchDashboardData()
    refreshTasks()
    startAutoRefresh()
})

// 在组件卸载时停止自动刷新
onUnmounted(() => {
    stopAutoRefresh()
})

// 趋势图表配置
const getTrendChartOption = computed(() => ({
    title: {
        text: '数据趋势分析'
    },
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data: ['数据量', '互动量']
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    toolbox: {
        feature: {
            saveAsImage: {}
        }
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: trendData.value.dates
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name: '数据量',
            type: 'line',
            data: trendData.value.data,
            smooth: true,
            lineStyle: {
                width: 2
            }
        },
        {
            name: '互动量',
            type: 'line',
            data: trendData.value.engagement,
            smooth: true,
            lineStyle: {
                width: 2
            }
        }
    ]
}))

// 来源分布图表配置
const getDistributionChartOption = computed(() => ({
    title: {
        text: '数据来源分布'
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
        orient: 'vertical',
        left: 'left',
        data: sourceData.value.labels
    },
    series: [
        {
            name: '数据来源',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '16',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: true
            },
            data: sourceData.value.labels.map((label, index) => ({
                value: sourceData.value.data[index],
                name: label
            }))
        }
    ]
}))
</script>

<style scoped>
.dashboard-container {
    padding: 20px;
}

.data-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-content {
    text-align: center;
}

.card-content h2 {
    margin: 10px 0;
    font-size: 24px;
    color: #303133;
}

.trend {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 5px;
}

.trend-value {
    font-weight: bold;
}

.trend-value.positive {
    color: #67c23a;
}

.trend-value.negative {
    color: #f56c6c;
}

.trend-label {
    color: #909399;
    font-size: 12px;
}

.chart-row {
    margin: 20px 0;
}

.chart-card {
    margin-bottom: 20px;
}

.chart-container {
    height: 400px;
    width: 100%;
}

.task-card {
    margin-bottom: 20px;
}

.el-progress {
    margin-top: 10px;
}

:deep(.echarts) {
    width: 100%;
    height: 100%;
}
</style> 